<?php

namespace app\common\service\qrcode;

use Grafika\Color;
use Grafika\Grafika;

class Birthday extends Base
{
    private $user;
    /**
     * 构造方法
     * Goods constructor.
     * @param $user
     */
    public function __construct($user)
    {
        parent::__construct();
        $this->user = $user ? $user : [];
    }

    /**
     * @return mixed
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function getImage()
    {
        // 判断海报图文件存在则直接返回url
        if (file_exists($this->getPosterPath())) {
            return $this->getPosterUrl();
        }
        // 商品海报背景图
        $backdrop = __DIR__ . '/resource/birthday_bg.png';
        $sex = "狮兄/姐";
        if($this->user['gender']==1) $sex = "狮兄";
        if($this->user['gender']==2) $sex = "狮姐";
       
        if (!$this->user['add_date'] || strtotime($this->user['add_date']) <= 0) {
            $age = 0;
        } else {
            $age = ceil(date('Y', time()) - date('Y', strtotime($this->user['add_date'])));//狮龄
        }
        if($age>0)
            $age_str = "您入会".$age."年了";
        else    
            $age_str = "您入会快1年了";
        $content = "          ".$this->user["nickName"].$sex."，今天是".date("Y年m月d日")."\n大连狮子会全体狮友祝贺您生日快乐！\n".$age_str."，感谢狮爱路上，益路同行。";
        // 拼接海报图
        return $this->savePoster($backdrop, $content);
    }

    /**
     * 拼接海报图
     * @param $backdrop
     * @param $goodsUrl
     * @param $qrcode
     * @return string
     * @throws \Exception
     */
    private function savePoster($backdrop, $content)
    {
        // 实例化图像编辑器
        $editor = Grafika::createEditor(['Gd']);
        // 字体文件路径
        $fontPath = Grafika::fontsDir() . '/' . 'st-heiti-light.ttc';
        // 打开海报背景图
        $editor->open($backdropImage, $backdrop);
        // 文字处理换行
        $fontSize = 19;
        //$content = $this->wrapText($fontSize, 0, $fontPath, $content, 500, 3);
        // 写入文字
        $editor->text($backdropImage, $content, $fontSize, 85, 970, new Color('#ff9900'), $fontPath);
        // 保存图片
        $editor->save($backdropImage, $this->getPosterPath());
        return $this->getPosterUrl();
    }

    /**
     * 处理文字超出长度自动换行
     * @param integer $fontsize 字体大小
     * @param integer $angle 角度
     * @param string $fontface 字体名称
     * @param string $string 字符串
     * @param integer $width 预设宽度
     * @param null $max_line 最多行数
     * @return string
     */
    private function wrapText($fontsize, $angle, $fontface, $string, $width, $max_line = null)
    {
        // 这几个变量分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度
        $content = "";
        // 将字符串拆分成一个个单字 保存到数组 letter 中
        $letter = [];
        for ($i = 0; $i < mb_strlen($string, 'UTF-8'); $i++) {
            $letter[] = mb_substr($string, $i, 1, 'UTF-8');
        }
        $line_count = 0;
        foreach ($letter as $l) {
            $testbox = imagettfbbox($fontsize, $angle, $fontface, $content . ' ' . $l);
            // 判断拼接后的字符串是否超过预设的宽度
            if (($testbox[2] > $width) && ($content !== "")) {
                $line_count++;
                if ($max_line && $line_count >= $max_line) {
                    $content = mb_substr($content, 0, -1, 'UTF-8') . "...";
                    break;
                }
                $content .= "\n";
            }
            $content .= $l;
        }
        return $content;
    }

    /**
     * 海报图文件路径
     * @return string
     */
    private function getPosterPath()
    {
        // 保存路径
        $tempPath = WEB_PATH . 'temp' . '/' . $this->user['wxapp_id'] . '/';
        !is_dir($tempPath) && mkdir($tempPath, 0755, true);
        return $tempPath . $this->getPosterName();
    }

    /**
     * 海报图文件名称
     * @return string
     */
    private function getPosterName()
    {
        return 'birthday_'.date('Y').'_' . md5("{$this->user["user_id"]}") . '.png';
    }

    /**
     * 海报图url
     * @return string
     */
    private function getPosterUrl()
    {
        return \base_url() . 'temp/' . $this->user['wxapp_id'] . '/' . $this->getPosterName() . '?t=' . time();
    }


}